package ren.nearby.main.web;

import android.content.Intent;
import android.graphics.PixelFormat;
import android.net.Uri;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ProgressBar;

import com.orhanobut.logger.Logger;
import com.tencent.smtt.export.external.interfaces.JsResult;
import com.tencent.smtt.sdk.CookieSyncManager;
import com.tencent.smtt.sdk.ValueCallback;
import com.tencent.smtt.sdk.WebChromeClient;
import com.tencent.smtt.sdk.WebSettings;
import com.tencent.smtt.sdk.WebView;
import com.tencent.smtt.sdk.WebViewClient;
import com.tencent.smtt.utils.TbsLog;

import java.net.MalformedURLException;
import java.net.URL;

import ren.nearby.http.base.BaseActivity;
import ren.nearby.main.R;


/**
 * Created by Administrator on 2018/4/8 0008.
 */

public class WebAct extends BaseActivity {
    private String mHomeUrl = "http://app.html5.qq.com/navi/index";
    private URL mIntentUrl;
    X5WebView x5WebView;

    //    @BindView(R2.id.main_fl_web)
    ViewGroup main_fl_web;
    //    @BindView(R2.id.main_pb)
    ProgressBar main_pb;

    //    @BindView(R2.id.main_ibtn_back)
    ImageButton main_ibtn_back;
    //    @BindView(R2.id.main_ibtn_forward)
    ImageButton main_ibtn_forward;







    //文件上传
    private ValueCallback<Uri> uploadFile;
    private ValueCallback<Uri[]> uploadFiles;

    @Override
    public int getContentView() {
        return R.layout.main_web;
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (x5WebView != null && x5WebView.canGoBack()) {
                x5WebView.goBack();
                if (Integer.parseInt(android.os.Build.VERSION.SDK) >= 16) {
//                    changGoForwardButton(mWebView);
                    return true;
                }
            } else {
                return super.onKeyDown(keyCode, event);
            }
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onDestroy() {
        if (x5WebView != null) {
            x5WebView.destroy();
        }
        super.onDestroy();
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        if (intent == null || x5WebView == null || intent.getData() == null) {
            return;
        }
        x5WebView.loadUrl(intent.getData().toString());
    }

    @Override
    public void onIntent() {
        super.onIntent();
        //网页中的视频，上屏幕的时候，可能出现闪烁的情况，需要如下设置：Activity在onCreate时需要设置:
        getWindow().setFormat(PixelFormat.TRANSLUCENT);
        Intent intent = getIntent();
        Uri uri = intent.getData();
        if (uri != null) {
            Logger.e(" uri != null ");
            String value1 = uri.getQueryParameter("value1");
            mHomeUrl = null;
            mHomeUrl = value1;
            String value2 = uri.getQueryParameter("value2");
            String value3 = uri.getQueryParameter("value3");
            Logger.e(mHomeUrl + " - " + value1 + " " + value2 + " " + value3);

        } else {
            Logger.e(" uri = null ");
        }

        if (intent != null) {
            try {
                mIntentUrl = new URL(intent.getData().toString());
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (NullPointerException e) {

            } catch (Exception e) {
            }
        }

        try {
            if (Integer.parseInt(android.os.Build.VERSION.SDK) >= 11) {
                getWindow()
                        .setFlags(
                                android.view.WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED,
                                android.view.WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED);
            }
        } catch (Exception e) {
        }
    }

    @Override
    public void initView() {
        super.initView();
        builder
                .setIconLeft(R.mipmap.btn_back_white)
                .setBack(true)
                .setTitle(getResources().getString(R.string.main_web))
                .setBackgroundColor(R.color.colorPrimary)
                .setTitleColor(R.color.white)
                .build();
        Logger.e(main_fl_web == null ? "1" : "0");
        Logger.e(main_pb == null ? "1" : "0");
        main_fl_web = findViewById(R.id.main_fl_web);
        main_pb = findViewById(R.id.main_pb);
        main_ibtn_back = findViewById(R.id.main_ibtn_back);
        main_ibtn_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (x5WebView != null && x5WebView.canGoBack()) {
                    x5WebView.goBack();
                }
            }
        });
        main_ibtn_forward = findViewById(R.id.main_ibtn_forward);
        main_ibtn_forward.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (x5WebView != null && x5WebView.canGoForward()) {
                    x5WebView.goForward();
                }
            }
        });
        init();
    }

    public void init() {
        x5WebView = new X5WebView(this, null);
        main_fl_web.addView(x5WebView,
                new FrameLayout.LayoutParams(
                        FrameLayout.LayoutParams.MATCH_PARENT,
                        FrameLayout.LayoutParams.MATCH_PARENT)
        );
        //设置进度条
        main_pb.setMax(100);

        main_pb.setProgressDrawable(this.getResources().getDrawable(R.drawable.main_color_progressbar));

        //设置webView基本信息
        x5WebView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                return false;
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);


            }
        });
        x5WebView.setWebChromeClient(new WebChromeClient() {
            @Override
            public boolean onJsConfirm(WebView webView, String s, String s1, JsResult jsResult) {
                return super.onJsConfirm(webView, s, s1, jsResult);
            }

            // For Android 3.0+
            public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType) {
                Logger.e("openFileChooser 1");
                WebAct.this.uploadFile = uploadFile;
                openFileChooseProcess();
            }

            // For Android < 3.0
            public void openFileChooser(ValueCallback<Uri> uploadMsgs) {
                Logger.e("openFileChooser 2");
                WebAct.this.uploadFile = uploadFile;
                openFileChooseProcess();
            }

            // For Android  > 4.1.1
            @Override
            public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) {
                Logger.e("openFileChooser 3");
                WebAct.this.uploadFile = uploadFile;
                openFileChooseProcess();
            }

            // For Android  >= 5.0
            @Override
            public boolean onShowFileChooser(com.tencent.smtt.sdk.WebView webView,
                                             ValueCallback<Uri[]> filePathCallback,
                                             WebChromeClient.FileChooserParams fileChooserParams) {
                Logger.e("openFileChooser 4:" + filePathCallback.toString());
                WebAct.this.uploadFiles = filePathCallback;
                openFileChooseProcess();
                return true;
            }


        });


        WebSettings webSetting = x5WebView.getSettings();
        webSetting.setAllowFileAccess(true);
        webSetting.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
        webSetting.setSupportZoom(true);
        webSetting.setBuiltInZoomControls(true);
        webSetting.setUseWideViewPort(true);
        webSetting.setSupportMultipleWindows(false);
        // webSetting.setLoadWithOverviewMode(true);
        webSetting.setAppCacheEnabled(true);
        // webSetting.setDatabaseEnabled(true);
        webSetting.setDomStorageEnabled(true);
        webSetting.setJavaScriptEnabled(true);
        webSetting.setGeolocationEnabled(true);
        webSetting.setAppCacheMaxSize(Long.MAX_VALUE);
        webSetting.setAppCachePath(this.getDir("appcache", 0).getPath());
        webSetting.setDatabasePath(this.getDir("databases", 0).getPath());
        webSetting.setGeolocationDatabasePath(this.getDir("geolocation", 0)
                .getPath());
        // webSetting.setPageCacheCapacity(IX5WebSettings.DEFAULT_CACHE_CAPACITY);
        webSetting.setPluginState(WebSettings.PluginState.ON_DEMAND);
        // webSetting.setRenderPriority(WebSettings.RenderPriority.HIGH);
        // webSetting.setPreFectch(true);
        long time = System.currentTimeMillis();
        if (mIntentUrl == null) {
            x5WebView.loadUrl(mHomeUrl);
        } else {
            x5WebView.loadUrl(mIntentUrl.toString());
        }
        TbsLog.d("time-cost", "cost time: "
                + (System.currentTimeMillis() - time));
        CookieSyncManager.createInstance(this);
        CookieSyncManager.getInstance().sync();
    }

    private void openFileChooseProcess() {
        Intent i = new Intent(Intent.ACTION_GET_CONTENT);
        i.addCategory(Intent.CATEGORY_OPENABLE);
        i.setType("*/*");
        startActivityForResult(Intent.createChooser(i, "test"), 0);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // TODO Auto-generated method stub
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case 0:
                    if (null != uploadFile) {
                        Uri result = data == null || resultCode != RESULT_OK ? null
                                : data.getData();
                        uploadFile.onReceiveValue(result);
                        uploadFile = null;
                    }
                    if (null != uploadFiles) {
                        Uri result = data == null || resultCode != RESULT_OK ? null
                                : data.getData();
                        uploadFiles.onReceiveValue(new Uri[]{result});
                        uploadFiles = null;
                    }
                    break;
                default:
                    break;
            }
        } else if (resultCode == RESULT_CANCELED) {
            if (null != uploadFile) {
                uploadFile.onReceiveValue(null);
                uploadFile = null;
            }

        }
    }
}
